package com.factory.test.m5622;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.factory.test.R;
import com.factory.test.activity.SystemInfoActivity;
import com.factory.test.base.BaseTestActivity;
import com.factory.test.databinding.ActivityM5622Network4gBinding;
import com.factory.test.util.DateTimeUtil;
import com.yecontech.sdk.base.util.SystemPropertiesProxy;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 网络4G测试
 */
public class Network4GActivity extends BaseTestActivity {

    private ActivityM5622Network4gBinding binding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_m5622_network_4g);

        TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String imsi = mTelephonyMgr.getDeviceId();
        if (imsi == null) {
            binding.message.setText("4G imei is null");
            binding.message.setTextColor(Color.parseColor("#FF0000"));
            return;
        }

        int simStat = mTelephonyMgr.getSimState();
        if (simStat != 5){
            binding.message.setText("4G sim card not ready");
            binding.message.setTextColor(Color.parseColor("#FF0000"));
            return;
        }
        mTelephonyMgr.listen(new PhoneStateListener(){
            @Override
            public void onSignalStrengthsChanged(SignalStrength signalStrength) {
                super.onSignalStrengthsChanged(signalStrength);
                //这个dbm 是2G和3G信号的值, 正常手机信号变化范围是从 -110dBm (差)到 -50dBm (好)之间
                int asu = signalStrength.getGsmSignalStrength();
                int dbm = -113 + 2 * asu;


                String desc = "";
                if (dbm > -75) {
                    desc = "网络很好";
                    binding.signal.setTextColor(context.getColor(R.color.activity_btn_color_green));
                } else if (dbm > -85) {
                    desc = "网络不错";
                    binding.signal.setTextColor(context.getColor(R.color.green));
                } else if (dbm > -95) {
                    desc = "网络还行";
                    binding.signal.setTextColor(Color.YELLOW);
                } else if (dbm > -100) {
                    desc = "网络很差";
                    binding.signal.setTextColor(Color.RED);
                } else {
                    desc = "网络错误";
                    binding.signal.setTextColor(Color.RED);
                }
                binding.signal.setText(desc);
                binding.signal.append(", 信号强度: " + dbm + "dBm");
            }
        }, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);

        String networktype = SystemInfoActivity.getNetworkToString(context);

        String baseband = SystemPropertiesProxy.getString(context, "gsm.version.baseband");
        binding.signal.setText(
                "IMEI:" + imsi + "\n" +
                        "IMSI:" + mTelephonyMgr.getSubscriberId() + "\n" +
                        "ICCID:" + mTelephonyMgr.getSimSerialNumber() + "\n" +
                        "version:" + baseband + "\n" +
                        "sim:" + simStat + "\n" +
                        "netWorkType:" + networktype + "\n" +
                        "testing ping www.baidu.com ... \n");
        binding.message.setTextColor(getResources().getColor(R.color.activity_btn_color_green));

        new Thread(){
            @Override
            public void run() {
                ping();
            }
        }.start();

        myTimerTask = new MyTimerTask();
        Timer t = new Timer();
        t.schedule(myTimerTask, 3000, 30 * 1000);

        try {
            pw = new PrintWriter(new FileOutputStream(new File(Environment.getExternalStorageDirectory(), "ping.log")));
        } catch (Exception e) {
            Log.e("file", "文件创建失败");
        }
    }


    private MyTimerTask myTimerTask;
    private int pingSuccessCount = 0;
    private int pingFailCount = 0;
    private PrintWriter pw;
    private class MyTimerTask extends TimerTask{
        @Override
        public void run() {
            boolean isPingSuccess = false;
            long startTime = SystemClock.elapsedRealtime();
            try {
                String ip = "www.baidu.com";
                isPingSuccess = InetAddress.getByName(ip).isReachable(3000);
            } catch (Exception e) {
                isPingSuccess = false;
            }

            long timeConsuming = SystemClock.elapsedRealtime() - startTime;
            if(isPingSuccess){
                pingSuccessCount ++;
            }else{
                pingFailCount ++;
            }

            try {
                String dateTime = DateTimeUtil.getCurrentTime("yyyy-MM-dd HH:mm:ss:SSS");
                pw.println(String.format("%s, ping www.baidu.com -> %s - %s", dateTime, isPingSuccess, timeConsuming));
                pw.flush();
            } catch (Exception e) {
                //e.printStackTrace();
            }

            handler.post(() -> {
                binding.ping.setText(String.format(Locale.CHINA, "ping成功:%d, 失败:%d", pingSuccessCount, pingFailCount));
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(myTimerTask != null){
            myTimerTask.cancel();
        }
    }

    private void ping(){
        Process process = null;
        DataOutputStream dataOutputStream = null;

        DataInputStream dataInputStream = null;

        try {
            process = Runtime.getRuntime().exec("su");
            dataOutputStream = new DataOutputStream(process.getOutputStream());
            dataOutputStream.writeBytes( "ping -c 3 -w 5000 www.baidu.com \n");
            dataOutputStream.writeBytes("exit\n");
            dataOutputStream.flush();
            process.waitFor();

            dataInputStream = new DataInputStream(process.getInputStream());
            int available = dataInputStream.available();
            if(available > 0){
                byte[] by = new byte[available];
                dataInputStream.read(by);
                String result = new String(by);
                Log.i("ping", result);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        binding.message.append(result);
                    }
                });
            }

            dataInputStream.close();
        } catch (Exception e) {
            //Log.e("adb", "shell exec fail ", e);
        } finally {
            try {
                if (dataOutputStream != null) {
                    dataOutputStream.close();
                }

                if (process != null) {
                    process.destroy();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
